import Api from "@/zdpui/api/api.js"
import {BASE_URL} from "@/config/base.js";
import {storage} from "@/zdpui/util/storage.js";
import msg from "@/zdpui/util/msg.js";

const req = new Api(BASE_URL)

// 请求拦截器
req.useRequestInterceptor(async (config, endpoint, method) => {
    const token = storage.get("token")
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
})

// 设置响应拦截器
req.useResponseInterceptor(async (response, data) => {
    // 响应码不为200,就是服务端错误
    if (response.status !== 200) {
        console.error(response)
        msg.error("服务器错误")
        return Promise.reject("服务端错误");
    }
    // 响应码不为10000,且status是false,一定是错误了
    if (data?.code !== 10000 && !data?.status) {
        console.error(data)
        msg.error(data?.msg ?? "服务器错误")
        return Promise.reject(data);
    }
    // 成功了
    return data?.data
})

export default req